package image2

import (
	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"image"
)

type Word struct {
	Word   string
	Length int
	X      int
	Y      int
}

type LineThrough struct {
	Color   string
	Height  int
	OffsetX int
	OffsetY int
}

type TextBackground struct {
	Color   string
	Opacity uint8
}

type text struct {
	Words          []Word
	Color          string
	Size           float64
	PaddingX       int
	LineHeight     int
	Font           *truetype.Font
	LineThrough    *LineThrough
	TextBackground *TextBackground
}

func (t *text) Process(canvas *Canvas) error {
	if err := t.processBackground(canvas); err != nil {
		return err
	}
	f := freetype.NewContext()
	// 设置分辨率
	f.SetDPI(72)
	// 设置字体
	f.SetFont(t.Font)
	// 设置尺寸
	f.SetFontSize(t.Size)
	// 设置画图区域
	f.SetClip(canvas.Canvas.Bounds())
	// 设置画到的资源
	f.SetDst(canvas.Canvas)
	// 设置颜色
	f.SetSrc(image.NewUniform(rgbaColor(t.Color, 255)))

	// 设置开始坐标 (lineHeight-size) 就是开始的偏移点
	// 我也不知道这里为什么要偏移3个像素 但他的确生效了
	var offset = 2
	if int(t.Size) != t.LineHeight {
		offset = int(t.Size - float64(t.LineHeight/2))
	}
	for _, w := range t.Words {
		pt := freetype.Pt(w.X, w.Y-offset)
		if _, err := f.DrawString(w.Word, pt); err != nil {
			return err
		}
	}

	return t.processLineThrough(canvas)
}

// 处理背景色
func (t *text) processBackground(canvas *Canvas) error {
	if t.TextBackground == nil {
		return nil
	}
	var opacity uint8 = 255
	if t.TextBackground.Opacity > 0 {
		opacity = t.TextBackground.Opacity
	}
	var color = rgbaColor(t.TextBackground.Color, opacity)
	var beginWidth, beginHeight, endWidth, endHeight int

	for _, w := range t.Words {
		beginWidth, beginHeight = w.X-t.PaddingX, w.Y-t.LineHeight
		endWidth, endHeight = beginWidth+w.Length+2*t.PaddingX, w.Y
		for x := beginWidth; x < endWidth; x++ {
			for y := beginHeight; y < endHeight; y++ {
				canvas.Placeholder[x][y] = 1
				canvas.Canvas.Set(x, y, color)
			}
		}
	}
	return nil
}

// 处理画横线
func (t *text) processLineThrough(canvas *Canvas) error {
	if t.LineThrough == nil {
		return nil
	}
	var color = rgbaColor(t.LineThrough.Color, 255)
	var beginWidth, beginHeight, endWidth, endHeight int
	offset := (t.LineThrough.Height + t.LineHeight) / 2
	for _, w := range t.Words {
		beginWidth, beginHeight = w.X+t.LineThrough.OffsetX, w.Y-offset+t.LineThrough.OffsetY
		endWidth, endHeight = beginWidth+w.Length-t.LineThrough.OffsetX, t.LineThrough.Height+beginHeight
		for x := beginWidth; x < endWidth; x++ {
			for y := beginHeight; y < endHeight; y++ {
				canvas.Canvas.Set(x, y, color)
			}
		}
	}
	return nil
}
